package com.ja.sevice.impl;

import java.text.DecimalFormat;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ja.config.WebsiteStateConfig;
import com.ja.dao.AgentMapper;
import com.ja.dao.JineMapper;
import com.ja.dao.LiushuiMapper;
import com.ja.dao.LuckyCountMapper;
import com.ja.dao.UserMapper;
import com.ja.domain.AdminUser;
import com.ja.domain.AgentTotal;
import com.ja.domain.AgentRecord;
import com.ja.domain.Jine;
import com.ja.domain.Liushui;
import com.ja.domain.Lsltjl;
import com.ja.domain.LuckyCount;
import com.ja.domain.PagingData;
import com.ja.domain.SetupAgent;
import com.ja.domain.TodayRecord;
import com.ja.domain.User;
import com.ja.sevice.LiushuiService;
import com.ja.sevice.YunyingbbService;
import com.ja.util.DateUtil;
import com.ja.util.JsonResult;

@Service
public class LiushuiServiceImpl implements LiushuiService{

	@Autowired
	private LiushuiMapper liushuiMapper;
	
	@Autowired
	private UserMapper userMapper;
    
	@Autowired
	private LuckyCountMapper luckycountMapper;
	
	@Autowired
	private AgentMapper agentMapper;
	
	@Autowired
	private JineMapper jineMapper;
	
	@Autowired
	private YunyingbbService yunyingbbService;
	
	/**
	 * 
	   *   方法名：flowChange   
	   *   描述：     添加流水记录                  TODO   
	   *   参数：    @param user 用户信息
	   *   参数：    @param admin 管理员信息
	   *   参数：    @param orderNum 相应订单号
	   *   参数：    @param total 变动金额
	   *   参数：    @param state 消费类型 true 充值  false 消费
	   *   参数：    @param model 变动类型
	   *   参数：    @return 
	 * @return: int
	 */
	public int flowChange(User user,AdminUser admin,String orderNum,double total,boolean state,String model) {  // TODO:
		user = userMapper.getUserByid(user.getId());
		double amount = 0.00;
		if(state) {
			amount = user.getBalance() + total;
		}else {
			amount = user.getBalance() - total;
		}
		Liushui flow = new Liushui();
		flow.setHuiyuanzh(user.getName());
		flow.setBdtype(model);
		flow.setBdqjine(user.getBalance());
		flow.setBdjine(total);
		flow.setBdhjine(amount);
		flow.setCreatetime(DateUtil.getCurrTime());
		flow.setOrdernum(orderNum);
		flow.setPeriod("-");
		flow.setCname("-");
		flow.setCzname(admin.getName());
		flow.setBeizhu(model);
		flow.setState(state);
		flow.setStatu(0);
		flow.setUser_type(user.getState());
		flow.setUserid(user.getId());
		user.setBalance(amount);
		user.setCreatetime(DateUtil.getCurrTime());
		liushuiMapper.addUserFlowingWaterRecrod(flow);
		userMapper.updateUserInfo(user);
		return 1;
	}
	
	@Override
	public int changeRecord(User user, AdminUser admin,String orderNum,  Double amount,Jine jine, String model,Integer type) {
		if(amount<=0.00) {
			return 1;
		}
		if (jine != null) {
			jine.setSqtime(DateUtil.getCurrTime());
			jine.setCltime(DateUtil.getCurrTime());
			jine.setOrdernum(orderNum);
			jine.setZhifupt(model);
			jine.setCkname("-");
			jine.setZhifuzh("-");
			jine.setState("充值成功");
			jine.setCaozuo("已操作");
			jine.setTikuanje(0.00);
			jine.setCzname(admin.getName());
			jineMapper.addJilu(jine);
			flowChange(user,admin,orderNum,amount,true,model);
		}else {
			flowChange(user,admin,orderNum,amount,true,model);
		}
		
		/**上级返点*/
		agentRebate(user,amount,1,orderNum);
		/** 抽奖次数 */
		double rechargeMoney = Double.parseDouble(WebsiteStateConfig.configs.get("rechargeMoney"));
		double returnMoney = Double.parseDouble(WebsiteStateConfig.configs.get("returnMoney"));
		if(rechargeMoney > 0.00 && returnMoney > 0.00) {
			double a = (amount / rechargeMoney) * returnMoney;
			if (amount >= rechargeMoney) {
				int cs = (int) a;
				LuckyCount counts = luckycountMapper.getOneLuckyCount(user.getId());
				counts.setCount(counts.getCount() + cs);
				counts.setUserid(user.getId());
				counts.setCreateTime(DateUtil.getCurrTime());
				luckycountMapper.updateLuckyCount(counts);
			}
		}
		return 0;
	}
	
	/**
	 * 多级代理返点计算
	 * @param user 用户信息
	 * @param amount 变动金额
	 * @param type 返点类型 1是充值 2是打码
	 * @param order_number 订单号
	 * @return
	 */
	public int agentRebate(User user, double amount,int type, String order_number) {
		AdminUser admin = new AdminUser();
		admin.setName("系统自动");
		List<SetupAgent> setups = agentMapper.findOpenAgentSetup(type);
		List<User> users = agentMapper.findAllSuperior(user.getId());
		if(users.size()<1||setups.size()<1) {  
			return 1;
		}
		int num = setups.size();
		if (setups.size() > users.size()) {
			num = users.size();
		}
		for (int i = 0; i < num; i++) {
			SetupAgent setup = setups.get(i);
			User u = users.get(i);
			double total = setup.getRebate_ratio() * amount;
			AgentRecord commonAgent = new AgentRecord(); 
			commonAgent.setAgent_name(u.getName());
			commonAgent.setAgent_grade(setup.getAgent_grade());
			commonAgent.setUser_name(user.getName());
			commonAgent.setConsume(amount);
			commonAgent.setOrder_number(order_number);
			commonAgent.setRebate_type(type);
			commonAgent.setRebate_ratio(setup.getRebate_ratio());
			commonAgent.setRebate_money(total);
			commonAgent.setCreated_time(DateUtil.getCurrTime());
			commonAgent.setAgent_id(u.getId());
			commonAgent.setUser_id(user.getId());
			agentMapper.insertAgentRecord(commonAgent);
			double rebate = u.getMoney();
			rebate += total;
			
			u.setMoney(rebate);
			u.setCreatetime(DateUtil.getCurrTime());    
			userMapper.updateUserInfo(u);
			AgentTotal ats = agentMapper.findAgentTotal(user.getId(),u.getId());
			AgentTotal at = new AgentTotal();
			if(ats == null) {
				at.setUser_name(user.getName());
				if(type==1) {
					at.setRecharge_money(amount);
					at.setCode_money(0.00);
				}else {
					at.setRecharge_money(0.00);
					at.setCode_money(amount);
				}
				at.setRebate_money(total);
				at.setBalance(user.getBalance()-amount);
				at.setAgent_grade(setup.getAgent_grade());
				at.setCreated_time(DateUtil.getCurrTime());
				at.setAgent_id(u.getId());
				at.setUser_id(user.getId());
				agentMapper.insertAgentTotal(at);
			}else {
				if(type==1) {
					ats.setRecharge_money(ats.getRecharge_money()+amount);
				}else {
					ats.setCode_money(ats.getCode_money()+amount);
				}
				ats.setRebate_money(ats.getRebate_money()+total);
				ats.setBalance(user.getBalance()-amount);
				ats.setCreated_time(DateUtil.getCurrTime());
				agentMapper.updateAgentTotal(ats);
			}
		}
		return 1;
	}
	
	@Override
	public int insideRecord(User user,AdminUser admin,String orderNum,Double amount,String model,Integer type) {
		switch (type) {
		case 1:
			flowChange(user,admin,orderNum,amount,true,model);
			break;
		case 2:
			flowChange(user,admin,orderNum,amount,false,model);
			break;
		}
		return 0;
	}
	
	@Override
	public int drawingRecord(User user, AdminUser admin, String orderNum, Double amount, Jine jine, String model,
			Integer type) {
		if(amount<=0.00) {
			return 1;
		}
		if(jine!=null) {
			jine.setHydengji("-");
			jine.setSkname(model);
			jine.setSkbankzh("-");
			jine.setSqtime("-");
			jine.setCltime(DateUtil.getCurrTime());
			jine.setOrdernum(orderNum);
			jine.setFukuanje(0.00);
			jine.setTikuanje(amount);
			jine.setState("提款成功");
			jine.setCaozuo("已操作");
			jine.setCzname(admin.getName());
			jineMapper.addJilu(jine);
		}
		// 流水
		switch (type) {
		case 1:
		case 2:
		case 5:
			flowChange(user,admin,orderNum,amount,false,model);
			break;
		case 3:
		case 4:
			flowChange(user,admin,orderNum,amount,true,model);
			break;
		}
		return 0;
	}
	
	@Override
	public int addActivityRecord(User user,String orderNum, boolean state, double amount, String model,Integer type) {
		AdminUser admin = new AdminUser();
		admin.setName("系统自动");
		flowChange(user,admin,orderNum,amount,state,model);
		return 0;
	}
	
	@Override
	public List<Liushui> getLiushui(Integer id) {
		return liushuiMapper.getLiushui(id);
	}
	
	@Override
	public List<Liushui> getAllJl(Integer integer, Integer integer2, int i) {
		return liushuiMapper.getAllJl(integer,integer2,i);
	}
	
	@Override
	public List<Liushui> getTypeJl(Integer integer, Integer integer2,Liushui l,String date1,String date2,int i) {
		return liushuiMapper.getTypeJl(integer,integer2,l,date1,date2,i);
	}
	
	@Override
	public List<Liushui> getOneLsJl(Liushui liushui, String date1, String date2, Integer id) {
		return liushuiMapper.getOneLsJl(liushui, date1, date2, id);
	}
	
	@Override
	public List<Liushui> getFanshuiJl() {
		return liushuiMapper.getFanshuiJl();
	}

	@Override
	public List<Liushui> getOneFanshui(Integer id) {
		return liushuiMapper.getOneFanshui(id);
	}
	
	@Override
	public int upliushui(Integer id) {
		return liushuiMapper.upliushui(id);
	}
	
	@Override
	public int weidu(Integer id) {
		return liushuiMapper.weidu(id);
	}
	
	@Override
	public Double getToday1(String cre1) {
		return liushuiMapper.getToday1(cre1);
	}
	
	@Override
	public double getToday2(String cre1) {
		return liushuiMapper.getToday2(cre1);
	}
	
	@Override
	public double getToday3(String cre1) {
		return liushuiMapper.getToday3(cre1);
	}
	
	@Override
	public double getToday4(String cre1) {
		return liushuiMapper.getToday4(cre1);
	}
	
	@Override
	public List<Liushui> getSignInRecord(Integer id) {
		return liushuiMapper.getSignInRecord(id);
	}
	
	@Override
	public List<Liushui> getAllSignInRecord() {
		return liushuiMapper.getAllSignInRecord();
	}
	
	@Override
	public Liushui checkSigIn(Integer id,String date) {
		return liushuiMapper.checkSigIn(id,date);
	}
	@Override
	public List<Lsltjl> query(String date) {
		return liushuiMapper.query(date);
	}
	@Override
	public User chax(Integer id) {
		return liushuiMapper.chax(id);
	}
	@Override
	public List<User> img(List<Integer> list) {
		return liushuiMapper.img(list);
	}
	
	@Override
	public List<User> findAgentUserList() {
		return userMapper.findAgentUserList();
	}
	
	@Override
	public List<User> findTermAgentList(User user) {
		return userMapper.findTermAgentList(user);
	}
	@Override
	public List<Liushui> getWDLiushui(Integer startIndex, Integer lineCount,Integer id, int model) {
		return liushuiMapper.getWDLiushui(startIndex,lineCount,id,model);   
	}
	@Override
	public List<Liushui> getYDLiushui(Integer startIndex, Integer lineCount,Integer id, int model) {
		return liushuiMapper.getYDLiushui(startIndex,lineCount,id,model);
	}
	
	@Override
	public void deleteliushui(Integer userid) {
		liushuiMapper.deleteliushui(userid);
	}
	
	@Override
	public List<Liushui> findByTimeDetails(String date) {
		return liushuiMapper.findByTimeDetails(date);
	}
	
	@Override
	public int receiveRebateMoney(Integer user_id) {
		User user = userMapper.getUserByid(user_id);
		Double receiveAReturnPoint = agentMapper.receiveAReturnPoint();
		if(user.getMoney() < receiveAReturnPoint) {
			return 2;
		}
		AdminUser admin = new AdminUser();
		admin.setName("系统自动");
		if(user.getMoney()>0.00) {
			flowChange(user, admin,"FD"+DateUtil.DateFormatOrderNum()+user_id, user.getMoney(), true, "代理返点");
			user.setMoney(0.00);
		}
		userMapper.updateUserInfo(user);
		return 0;
	}
	@Override
	public Integer getWDLiushuiCounts(Integer id,int state) { 
		return liushuiMapper.getWDLiushuiCounts(id,state);
	}
	@Override
	public Integer getAllJlCounts() {
		return liushuiMapper.getAllJlCounts();
	}
	@Override
	public Integer getTypeJlCounts(Liushui liushui, String date1, String date2) {
		return liushuiMapper.getTypeJlCounts(liushui, date1, date2);
	}
	
	@Override
	public Integer getLiushuiCounts(Liushui liushui) {
		return liushuiMapper.getLiushuiCounts(liushui);
	}
	
	@Override
	public List<Liushui> getLiushuis(PagingData paging,Liushui liushui) {
		return liushuiMapper.getLiushuis(paging, liushui);
	}
	@Override
	public Double checkinTotal(Integer userid) {
		return liushuiMapper.checkinTotal(userid);
	}
	/**
	 * synchronized 将该方法锁住   测试的时候发现同一时间进去了两个
	 */
	@Transactional
	@Override
	public synchronized JsonResult  signInUserIng(User users) {
		DecimalFormat dec = new DecimalFormat("#0.00");
		String message = "";
		Liushui water = liushuiMapper.checkSigIn(users.getId(), DateUtil.getCurrTime());//查询用户今日的签到情况
		TodayRecord record = yunyingbbService.findOperateRecord("", "", users.getName(),2);
		Double signTotal1 = record.getMrqiandao();//用户的签到总计
		if (water != null) {
			message = "6";//等于6就是已经签到过了
			User user = userMapper.getUserByid(users.getId());
			return new JsonResult(message,user.getBalance()+";"+water.getBdjine()+";"+signTotal1);
		}
		Double lishi = record.getChongzhi();//用户的充值总计
		TodayRecord record2 = liushuiMapper.findByTimeUserRechargeTotal(DateUtil.findFormatDate(),DateUtil.getLast12Months(0),users.getId());
		Double benyue = record2.getZxtikuan()+record2.getRgkoukuan();//用户的本月充值总计
		Double jinri = record2.getZxchongzhi()+record2.getRgjiakuan();//用户的今日充值总计
		
		if (Integer.parseInt(WebsiteStateConfig.configs.get("qiandaoflag")) == 0) {
			message = "0";//等于0签到功能已经关闭
			return new JsonResult(message, signTotal1);
		}
		double qiandao = 0.00;
		double mrsx = Double.parseDouble(WebsiteStateConfig.configs.get("meiriMoney"));
		double mysx = Double.parseDouble(WebsiteStateConfig.configs.get("meiyueMoney"));
		double lssx = Double.parseDouble(WebsiteStateConfig.configs.get("lishiMoney"));
		double yesx = Double.parseDouble(WebsiteStateConfig.configs.get("yueMoney"));
		double suiji = Double.parseDouble(WebsiteStateConfig.configs.get("moneySuiji"));
		User user = userMapper.getUserByid(users.getId());
		if(yesx != 0) {
			if ( user.getBalance() < yesx) {
				message = "1";//签到账户余额不足，为1
				return new JsonResult(message, user.getBalance()+";"+yesx+";"+signTotal1);
			}
		}
		if(mrsx != 0) {
			if (jinri < mrsx) {
				message = "2";//今日充值金额不足 ，为 2
				return new JsonResult(message, user.getBalance()+";"+mrsx+";"+signTotal1);
			}
		} 
		if(mysx != 0) {
			if (benyue < mysx) {
				message = "3";//本月充值金额不足, 为3
				return new JsonResult(message, user.getBalance()+";"+mysx+";"+signTotal1);
			}
		}
		if(lssx != 0) {
			if (lishi < lssx) {
				message = "4";//历史充值金额不足 为4
				return new JsonResult(message, user.getBalance()+";"+lssx+";"+signTotal1);
			}
		}
		if (Integer.parseInt(WebsiteStateConfig.configs.get("moneyType")) == 0) {
			qiandao = Math.random() * suiji;
		} else {
			qiandao = Double.parseDouble(WebsiteStateConfig.configs.get("moneyGuding"));
		}
		String orderNum = "QD"+DateUtil.DateFormatOrderNum()+user.getId();
		AdminUser admins = new AdminUser();
		admins.setName("系统自动");
		flowChange(user,admins,orderNum,qiandao,true,"每日签到");
		message = "5";//签到成功为5
		User u = userMapper.getUserByid(user.getId());
		record = yunyingbbService.findOperateRecord("", "", users.getName(),2);
		signTotal1 = record.getMrqiandao();//用户的签到总计
		return new JsonResult(message,  u.getBalance()+";"+dec.format(qiandao)+";"+signTotal1);
	}

	@Override
	public List<Liushui> findWaterData() {
		return liushuiMapper.findWaterData();
	}

	@Override
	public void updateWaterData(Liushui liushui) {
		liushuiMapper.updateWaterData(liushui);
		
	}

}
